<template>
  <div class="color-change-container">
    <input type="text" maxlength="10" v-model="color" />
    <hr />
    <p>输入的颜色: {{color}}</p>
    <hr />
    <div>转换后的颜色: {{result}}</div>
    <hr />
    <button @click="change()">转换颜色</button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      color: "",
      result: ""
    };
  },
  methods: {
    change() {
      // //十六进制颜色值的正则表达式
      let reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;

      var that = this;
      //十六进制颜色值的正则表达式

      // 如果是rgb颜色表示
      if (/^(rgb|RGB)/.test(that)) {
        var aColor = that.replace(/(?:\(|\)|rgb|RGB)*/g, "").split(",");
        var strHex = "#";
        for (var i = 0; i < aColor.length; i++) {
          var hex = Number(aColor[i]).toString(16);
          if (hex === "0") {
            hex += hex;
          }
          strHex += hex;
        }
        if (strHex.length !== 7) {
          strHex = that;
        }
        return strHex;
      } else if (reg.test(that)) {
        var aNum = that.replace(/#/, "").split("");
        if (aNum.length === 6) {
          return that;
        } else if (aNum.length === 3) {
          var numHex = "#";
          for (var i = 0; i < aNum.length; i += 1) {
            numHex += aNum[i] + aNum[i];
          }
          return numHex;
        }
      }
    }
  }
};
</script>
<style lang='scss' type='text/scss' scoped>
.color-change-container {
  padding: 100px;
}
</style>